import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel
from PySide6.QtCore import QThread, Signal


class WorkerThread(QThread):
    update_signal = Signal(int)  # 定义信号

    def run(self):
        for i in range(1, 101):
            self.msleep(50)  # 模拟耗时操作
            self.update_signal.emit(i)  # 发射信号


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.thread = None
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('QThread示例')
        self.setGeometry(300, 300, 300, 200)

        self.label = QLabel('准备开始', self)
        self.btn_start = QPushButton('开始任务', self)
        self.btn_stop = QPushButton('停止任务', self)

        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.btn_start)
        layout.addWidget(self.btn_stop)
        self.setLayout(layout)

        self.thread = WorkerThread()
        self.btn_start.clicked.connect(self.start_task)
        self.btn_stop.clicked.connect(self.stop_task)
        self.thread.update_signal.connect(self.update_progress)

    def start_task(self):
        self.thread.start()
        self.label.setText('任务进行中...')

    def stop_task(self):
        self.thread.terminate()
        self.label.setText('任务已停止')

    def update_progress(self, value):
        self.label.setText(f'进度: {value}%')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
